package com.maodou.android.ui.page.web

import android.annotation.SuppressLint
import android.content.ActivityNotFoundException
import android.content.Intent
import android.graphics.Bitmap
import android.net.Uri
import android.net.http.SslError
import android.os.Build
import android.os.Message
import android.view.WindowManager
import android.webkit.CookieManager
import android.webkit.SslErrorHandler
import android.webkit.ValueCallback
import android.webkit.WebResourceRequest
import android.webkit.WebSettings
import android.webkit.WebView
import androidx.activity.ComponentActivity
import androidx.activity.compose.BackHandler
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.WindowInsets
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.ime
import androidx.compose.foundation.layout.padding
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.outlined.KeyboardArrowLeft
import androidx.compose.material3.LinearProgressIndicator
import androidx.compose.material3.MaterialTheme
import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableFloatStateOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.platform.LocalLifecycleOwner
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleEventObserver
import androidx.compose.ui.unit.dp
import androidx.compose.ui.viewinterop.AndroidView
import com.just.agentweb.WebChromeClient
import com.just.agentweb.WebViewClient
import com.maodou.android.ui.page.WebViewKey
import com.maodou.core.navigation.Navigator3
import com.maodou.core.ui.components.ActionBar
import com.maodou.core.ui.components.TitleAlignment
import java.net.URLDecoder

import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.result.contract.ActivityResultContracts
import androidx.compose.material3.Text
import androidx.compose.material3.ProgressIndicatorDefaults
import androidx.compose.ui.draw.alpha
import androidx.core.net.toUri

/**
 * @Author Xing
 * @CreateTime 2025年09月28日
 * @Description 通过AndroidView展示webview
 */
@SuppressLint("UnrememberedMutableState", "ContextCastToActivity", "SetJavaScriptEnabled")
@Composable
fun WebViewScreen(
    key: WebViewKey,
) {
    val imeInsets = WindowInsets.ime
    var filePathCallback by mutableStateOf<ValueCallback<Array<Uri>>?>(null)
    val context = LocalContext.current as ComponentActivity

    // 文件选择器，用于处理 WebChromeClient.onShowFileChooser 回调
    val fileChooserLauncher = rememberLauncherForActivityResult(ActivityResultContracts.GetContent()) { uri ->
        if (uri != null) {
            filePathCallback?.onReceiveValue(arrayOf(uri))
        } else {
            filePathCallback?.onReceiveValue(null)
        }
        filePathCallback = null
    }
    // 页面错误状态（如网络错误/SSL错误）
    var pageError by remember { mutableStateOf<String?>(null) }

    Column(
        modifier = Modifier
            .fillMaxSize()
            .background(color = Color(0xffffffff))
            .padding(bottom = with(LocalDensity.current) {
                imeInsets.getBottom(this).toDp()
            })
    ) {

        var loading by rememberSaveable { mutableStateOf(false) }
        var canGoBack by remember { mutableStateOf(false) }
        var title by remember { mutableStateOf("") }
        var progress by remember { mutableFloatStateOf(0f) }
        var finalUrl by remember { mutableStateOf("") }
        var contentCommitted by rememberSaveable { mutableStateOf(false) }

        val webView = remember {
            WebView(context).apply {
                val web = this
                settings.apply {
                    javaScriptEnabled = true
                    loadWithOverviewMode = true
                    useWideViewPort = true
                    defaultFontSize = 14
                    cacheMode = WebSettings.LOAD_DEFAULT
                    domStorageEnabled = true
                    javaScriptCanOpenWindowsAutomatically = true
                    setSupportMultipleWindows(true)
                    allowFileAccess = true
                    databaseEnabled = true
                    setGeolocationEnabled(true)
                    userAgentString =
                        "Mozilla/5.0 (Linux; Android 10; Mobile) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/96.0.4664.104 Mobile Safari/537.36"
                    mixedContentMode = WebSettings.MIXED_CONTENT_COMPATIBILITY_MODE
                    offscreenPreRaster = true
                }
                this.setBackgroundColor(android.graphics.Color.TRANSPARENT)
                // Cookie 配置（含第三方 Cookie）
                CookieManager.getInstance().apply {
                    setAcceptCookie(true)
                    setAcceptThirdPartyCookies(web, true)
                }
                // 下载处理，交由系统处理（可对接 DownloadManager）
                setDownloadListener { url, _, _, _, _ ->
                    try {
                        context.startActivity(Intent(Intent.ACTION_VIEW, url.toUri()))
                    } catch (e: Exception) {
                        e.printStackTrace()
                    }
                }

                clearCache(true)
                clearHistory()

                this.setOnFocusChangeListener { _, hasFocus ->
                    if (hasFocus) {
                        try {
                            val activity = context
                            activity.window.setSoftInputMode(
                                WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE
                            )
                        } catch (e: Exception) {
                            e.printStackTrace()
                        }
                    }
                }

            }
        }

        LaunchedEffect(Unit) {
            try {
                val activity = context
                activity.window?.setSoftInputMode(
                    WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE
                )
            } catch (e: Exception) {
                e.printStackTrace()
            }
        }

        LaunchedEffect(key.url) {
            finalUrl = if (key.url.contains("%") && try {
                    val decoded = URLDecoder.decode(key.url, "UTF-8")
                    decoded != key.url
                } catch (e: Exception) {
                    false
                }
            ) {
                URLDecoder.decode(key.url, "UTF-8")
            } else key.url

            // 新开页面前重置内容可见标记
            contentCommitted = false
            webView.loadUrl(finalUrl)
        }

        val back: () -> Unit = {
            if (canGoBack) {
                webView.goBack()
            } else {
                Navigator3.pop()
            }
        }

        BackHandler {
            back()
        }

        ActionBar(
            title = title,
            modifier = Modifier.fillMaxWidth(),
            navigationIcon = Icons.AutoMirrored.Outlined.KeyboardArrowLeft,
            onNavigationClick = { back() },
            backgroundColor = Color.Transparent,
            contentColor = MaterialTheme.colorScheme.onSurface,
            titleAlignment = TitleAlignment.Center,
        )

        if (progress < 1f) {
            LinearProgressIndicator(
                progress = { progress },
                modifier = Modifier
                    .fillMaxWidth()
                    .height(3.dp),
                color = MaterialTheme.colorScheme.primary,
                trackColor = MaterialTheme.colorScheme.primary.copy(alpha = 0.15f),
                strokeCap = ProgressIndicatorDefaults.LinearStrokeCap,
            )
        }
        Column(
            modifier = Modifier.fillMaxSize()
        ) {
            AndroidView(
                modifier = Modifier.weight(1f).alpha(if (contentCommitted) 1f else 0.001f),
                factory = {
                    webView
                },
                update = {
                    it.webChromeClient = object : WebChromeClient() {

                        override fun onCreateWindow(
                            view: WebView?,
                            isDialog: Boolean,
                            isUserGesture: Boolean,
                            resultMsg: Message?
                        ): Boolean {
                            val child = WebView(context).apply {
                                settings.javaScriptEnabled = true
                                settings.domStorageEnabled = true
                                settings.setSupportMultipleWindows(true)
                                webViewClient = object : WebViewClient() {
                                    override fun onPageStarted(v: WebView?, url: String?, favicon: Bitmap?) {
                                        if (!url.isNullOrEmpty()) {
                                            webView.loadUrl(url)
                                        }
                                        try { v?.stopLoading() } catch (_: Exception) {}
                                        this@apply.post { try { destroy() } catch (_: Exception) {} }
                                    }
                                }
                            }
                            val transport = resultMsg?.obj as? WebView.WebViewTransport ?: return false
                            transport.webView = child
                            resultMsg.sendToTarget()
                            return true
                        }

                        override fun onProgressChanged(view: WebView?, newProgress: Int) {
                            super.onProgressChanged(view, newProgress)
                            progress = newProgress / 100f
                        }

                        override fun onShowCustomView(
                            view: android.view.View?,
                            callback: CustomViewCallback?
                        ) {
                            super.onShowCustomView(view, callback)
                            try {
                                val activity = context
                                activity.window.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE)
                            } catch (e: Exception) {
                                e.printStackTrace()
                            }
                        }

                        // 接收页面标题，及时更新顶部栏标题
                        override fun onReceivedTitle(view: WebView?, newTitle: String?) {
                            super.onReceivedTitle(view, newTitle)
                            title = newTitle ?: title
                        }

                        override fun onShowFileChooser(
                            p0: WebView?,
                            filePath: ValueCallback<Array<Uri>>?,
                            p2: FileChooserParams?
                        ): Boolean {
                            filePathCallback = filePath // 保存回调引用
                            // 启动系统文件选择器
                            fileChooserLauncher.launch("*/*")
                            return true
                        }
                    }

                    it.webViewClient = object : WebViewClient() {

                        override fun onPageStarted(
                            view: WebView?,
                            url: String?,
                            favicon: Bitmap?
                        ) {
                            super.onPageStarted(view, url, favicon)
                            loading = true
                            progress = 0f
                            pageError = null
                            contentCommitted = false
                            try { webView.setLayerType(android.view.View.LAYER_TYPE_HARDWARE, null) } catch (_: Exception) {}
                        }

                        override fun shouldOverrideUrlLoading(
                            view: WebView?,
                            request: WebResourceRequest?
                        ): Boolean {
                            val u = request?.url?.toString() ?: return false
                            return handleUrl(view, u)
                        }

                        override fun shouldOverrideUrlLoading(view: WebView?, url: String?): Boolean {
                            val u = url ?: return false
                            return handleUrl(view, u)
                        }

                        private fun handleUrl(view: WebView?, url: String): Boolean {
                            return try {
                                when {
                                    url.startsWith("http://") || url.startsWith("https://") -> {
                                        false
                                    }
                                    url.startsWith("intent://") -> {
                                        val intent = Intent.parseUri(url, Intent.URI_INTENT_SCHEME)
                                        val exist = intent.resolveActivity(context.packageManager) != null
                                        if (exist) {
                                            context.startActivity(intent)
                                        } else {
                                            val fallback = intent.getStringExtra("browser_fallback_url")
                                            if (!fallback.isNullOrEmpty()) {
                                                view?.loadUrl(fallback)
                                            }
                                        }
                                        true
                                    }
                                    else -> {
                                        val intent = Intent(Intent.ACTION_VIEW, Uri.parse(url))
                                        try {
                                            context.startActivity(intent)
                                            true
                                        } catch (e: ActivityNotFoundException) {
                                            false
                                        }
                                    }
                                }
                            } catch (e: Exception) {
                                e.printStackTrace()
                                false
                            }
                        }

                        override fun onPageCommitVisible(view: WebView?, url: String?) {
                            contentCommitted = true
                            try { webView.setLayerType(android.view.View.LAYER_TYPE_NONE, null) } catch (_: Exception) {}
                        }

                        override fun onPageFinished(view: WebView?, url: String?) {
                            super.onPageFinished(view, url)
                            canGoBack = webView.canGoBack()
                            title = view?.title ?: title
                            loading = false
                            progress = 1f
                            if (!contentCommitted) {
                                contentCommitted = true
                            }
                            try { webView.setLayerType(android.view.View.LAYER_TYPE_NONE, null) } catch (_: Exception) {}
                        }

                        // 页面加载错误处理
                        override fun onReceivedError(
                            view: WebView?,
                            request: WebResourceRequest?,
                            error: android.webkit.WebResourceError?
                        ) {
                            super.onReceivedError(view, request, error)
                            pageError = error?.description?.toString() ?: "页面加载失败"
                            loading = false
                            progress = 1f
                            try { webView.setLayerType(android.view.View.LAYER_TYPE_NONE, null) } catch (_: Exception) {}
                        }

                        override fun onReceivedSslError(
                            view: WebView?,
                            handler: SslErrorHandler?,
                            error: SslError?
                        ) {
                            handler?.cancel()
                        }
                    }
                }
            )
//
            // 如页面加载失败，展示简单错误提示（可按需替换为自定义错误页）
//            if (pageError != null) {
//                Text(
//                    text = pageError ?: "",
//                    color = Color(0xFFD32F2F),
//                    modifier = Modifier
//                        .fillMaxWidth()
//                        .background(Color(0x1AF44336))
//                        .padding(12.dp)
//                )
//            }
            Spacer(modifier = Modifier.height(8.dp))
        }

        DisposableEffect(Unit) {
            onDispose {
                webView.apply {
                    stopLoading()
                    // 若文件选择器尚未返回，必须回调 null 以避免卡住
                    if (filePathCallback != null) {
                        try { filePathCallback?.onReceiveValue(null) } catch (_: Exception) {}
                        filePathCallback = null
                    }
                    destroy()
                }
            }
        }
        val lifecycleOwner = LocalLifecycleOwner.current
        DisposableEffect(lifecycleOwner, webView) {
            val observer = LifecycleEventObserver { _, event ->
                when (event) {
                    Lifecycle.Event.ON_START, Lifecycle.Event.ON_RESUME -> {
                        try {
                            webView.onResume()
                            webView.resumeTimers()
                        } catch (_: Exception) {}
                    }
                    Lifecycle.Event.ON_PAUSE, Lifecycle.Event.ON_STOP -> {
                        try {
                            webView.onPause()
                            webView.pauseTimers()
                        } catch (_: Exception) {}
                    }
                    Lifecycle.Event.ON_DESTROY -> {
                        try {
                            webView.apply {
                                stopLoading()
                                loadUrl("about:blank")
                                clearCache(true)
                                clearHistory()
                                removeAllViews()
                                if (filePathCallback != null) {
                                    try { filePathCallback?.onReceiveValue(null) } catch (_: Exception) {}
                                    filePathCallback = null
                                }
                                destroy()
                            }
                            try { CookieManager.getInstance().flush() } catch (_: Exception) {}
                        } catch (_: Exception) {}
                    }
                    else -> {}
                }
            }
            lifecycleOwner.lifecycle.addObserver(observer)
            onDispose {
                lifecycleOwner.lifecycle.removeObserver(observer)
                webView.apply {
                    stopLoading()
                    loadUrl("about:blank")
                    clearCache(true)
                    clearHistory()
                    removeAllViews()
                    if (filePathCallback != null) {
                        try { filePathCallback?.onReceiveValue(null) } catch (_: Exception) {}
                        filePathCallback = null
                    }
                    destroy()
                }
                try { CookieManager.getInstance().flush() } catch (_: Exception) {}
            }
        }
    }
}